<?php
/**
 * Created by PhpStorm.
 * User: 吴登科
 * Date: 2018/10/11
 * Time: 10:15
 * 优惠券管理
 */

namespace Admin\Controller;

use Think\Image;
use Think\Upload;

class CouponController extends PublicController
{
    function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 优惠券管理列表
     */
    public function index()
    {
        $wadmin = session("wadmin");//当前店铺管理员信息
        if ($wadmin['store_id'] == 0) {
            $map = '';
        } else {
            $map['c.store_id'] = $wadmin['store_id'];
        }

        $count = M("coupon")->alias("c")->where($map)->count(); // 查询满足要求的总记录数
        $Page = new \Think\Page($count, 10);// 实例化分页类 传入总记录数和每页显示的记录数
        $Page->setConfig('theme', "<ul class='pagination no-margin pull-right'></li><li>%FIRST%</li><li>%UP_PAGE%</li><li>%LINK_PAGE%</li><li>%DOWN_PAGE%</li><li>%END%</li><li><a> %HEADER%  %NOW_PAGE%/%TOTAL_PAGE% 页</a></ul>");//(对thinkphp自带分页的格式进行自定义)
        $show = $Page->show(); // 分页显示输出
        $result = M("coupon")->alias("c")
            ->join("meal_store as s on c.store_id=s.store_id")
            ->field("c.*,s.store_name")
            ->where($map)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->order("c.coupon_id desc")
            ->select();

//        dump($result);die;

        //判断优惠券是否过期
        foreach($result as $value){
            if($value['use_end_time']<=time()){
               M('coupon')->where(['coupon_id'=>$value['coupon_id']])->setField(['status'=>0]);
            }
        }

        $this->assign("result", $result);
        $this->assign("page", $show); // 赋值分页输出
        $this->display();
    }

    /**
     * 添加优惠券
     */
    public function add()
    {
        $wadmin = session("wadmin");
        if ($wadmin['store_id'] == 0) {
            $storeId = 0;
        } else {
            $storeId = $wadmin['store_id'];
        }

        //店铺信息（所有的店铺）
        $store = M('store')->field('store_id,store_name')->select();

        $this->assign("storeId", $storeId);
        $this->assign("store", $store);
        $this->display();
    }

    /**
     * 添加操作
     */
    public function addSave()
    {
        $data = I("post.");
        if ($data && is_array($data)) {
            if (preg_match("/^[1-9]\d*(\.\d+)?$/", $data['money']) == 0) {
                $this->error("请输入正确的优惠券价格");
            }

            if (preg_match("/^[1-9]\d*(\.\d+)?$/", $data['condition_money']) == 0) {
                $this->error("请输入正确的条件价格");
            }

            $wadmin = session("wadmin");
            if ($wadmin) {
                $data['creater'] = $wadmin['user_name']; //登录管理员
            } else {
                $data['creater'] = "";
            }

            if (!empty($data['use_start_time'])) {
                $data['use_start_time'] = strtotime($data['use_start_time']);
            } else {
                $this->error("请输入正确的开始时间");
            }
            if (!empty($data['use_end_time'])) {
                $data['use_end_time'] = strtotime($data['use_end_time']);
            } else {
                $this->error("请输入正确的结束时间");
            }

            if ($wadmin['store_id'] == 0) {
                $data['store_id'] = $data['store_id']; // 店铺ID
            } else {
                $data['store_id'] = $wadmin['store_id']; // 店铺ID
            }

            $data['add_time'] = time();
            $result = M('coupon')->add($data);
            if ($result !== false) {
                $this->success("新增成功！", U('Admin/coupon/index'));
            } else {
                $this->error("操作失败");
            }
        } else {
            $this->error("操作失败");
        }
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $store_id = session("wadmin");
        if ($store_id['store_id'] == 0) {
            $storeId = 0;
        } else {
            $storeId = $store_id['store_id'];
        }

        $id = I("get.id");
        $result = M("coupon")->where(array("coupon_id" => $id))->field('coupon_id,name,money,use_start_time,use_end_time,condition_money,store_id,type')->find();

        //将时间戳转换成日期格式
        $result['use_start_time'] = date("Y-m-d ", $result['use_start_time']);
        $result['use_end_time'] = date("Y-m-d ", $result['use_end_time']);

        //店铺信息（所有的店铺）
        $store = M('store')->field('store_id,store_name')->select();
        $this->assign("storeId", $storeId); //店铺id(登录的)
        $this->assign("store", $store);
        $this->assign("result", $result);
        $this->display();
    }


    /**
     * 编辑操作
     */
    public function save()
    {
        $data = I("post.");

        if ($data && is_array($data)) {
            if (preg_match("/^[1-9]\d*(\.\d+)?$/", $data['money']) == 0) {
                $this->error("请输入正确的优惠券价格");
            }

            if (preg_match("/^[1-9]\d*(\.\d+)?$/", $data['condition_money']) == 0) {
                $this->error("请输入正确的条件价格");
            }

            $id = $data['coupon_id'];
            //查找是否存在
            $coupon = M("coupon")->where(array("coupon_id" => $id))->find();

            $store_id = session("wadmin");
            if ($store_id) {
                $data['creater'] = $store_id['user_name']; //登录管理员
            } else {
                $data['creater'] = "";
            }

            if (!empty($data['use_start_time'])) {
                $data['use_start_time'] = strtotime($data['use_start_time']);
            } else {
                $this->error("请输入正确的开始时间");
            }
            if (!empty($data['use_end_time'])) {
                $data['use_end_time'] = strtotime($data['use_end_time']);
            } else {
                $this->error("请输入正确的结束时间");
            }

            if ($coupon) {
                $result = M("coupon")->where("coupon_id='$id'")->save($data);
                if ($result !== false) {
                    $this->success("修改成功！", U('Admin/coupon/index'));
                } else {
                    $this->error("操作失败");
                }
            } else {
                $this->error("优惠券不存在");
            }
        } else {
            $this->error("操作失败");
        }
    }

    /**
     * 删除
     */
    public function del()
    {
        $id = I("get.id");
        $result = M("coupon")->where(array("coupon_id" => $id))->delete();
        if ($result !== false) {
            $this->success("删除优惠券成功！");
        } else {
            $this->error("操作失败");
        }
    }
}